import axios from "axios";

const myAxios = axios.create({
    baseURL: 'http://localhost:8080/api',
    withCredentials: true
});

// 请求拦截器
myAxios.interceptors.request.use(
    config => {
        console.log("[Request]", config);
        return config;
    },
    error => {
        console.error("[Request Error]", error);
        return Promise.reject(error);
    }
);

// 响应拦截器修正版
myAxios.interceptors.response.use(response => {
    if (response?.data?.code === 40100) {
        const redirectUrl = encodeURIComponent(window.location.href);
        window.location.href = `/user/login?redirect=${redirectUrl}`;
        return Promise.reject(new Error('需要登录'));
    }
    return response.data;
}, error => {
    if (error.response?.status === 401) {
        const redirectUrl = encodeURIComponent(window.location.href);
        window.location.href = `/user/login?redirect=${redirectUrl}`;
    }
    return Promise.reject(error);
});



export default myAxios;